<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/5/21
 * Time: 21:53
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;
use app\lib\exception\WeChatException;
use think\Exception;
use think\Cache;
use app\api\model\User as UserModel;

class UserToken extends Token
{
    protected $code;
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxLoginUrl
;
    function __construct($code)
    {
        $this->code = $code;
        $this->wxAppID = config('wx_b.app_id');
        $this->wxAppSecret = config('wx_b.app_secret');
        $this->wxLoginUrl = sprintf(config('wx_b.login_url'),
            $this->wxAppID,$this->wxAppSecret,$this->code);
    }

    public function get() {

        $result = curl_get($this->wxLoginUrl);
        $wxResult = json_decode($result,true); //true 为数组，false为对象
        if(empty($wxResult)) {
            throw new Exception('获取session_key及openID时异常，微信内部错误');
        }else{
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail) {
                $this->processLoginError($wxResult);
            }else{
               return $this->grantToken($wxResult);
            }
        }
    }

    public function getOpenId() {
        $result = curl_get($this->wxLoginUrl);
        $wxResult = json_decode($result,true); //true 为数组，false为对象
        if(empty($wxResult)) {
            throw new Exception('获取session_key及openID时异常，微信内部错误');
        }else{
            return $openId = $wxResult['openid'];
        }
    }
    private function grantToken($wxResult) {
        //拿到openid
        //检查数据库openid是否已经存在
        //如果存在，则不处理，如果不存在，则新增一条user记录
        //生成令牌，准备缓存数据，写入缓存
        //把令牌返回到客户端
        //key:令牌 token
        //value:wxResult,uid,scope
        $openid = $wxResult['openid'];
        $user = UserModel::getByOpenID($openid);
        if($user) {
            $uid = $user->id;
        }else{
            $uid = $this->newUser($openid);
        }
        $cachedValue = $this->prepareCachedValue($wxResult,$uid);
        $token = $this->saveToCache($cachedValue);
        return $token;

    }
    private function saveToCache($cachedValue) {
        $key = self::generateToken();
        $value = json_encode($cachedValue);
        $expire_in = config('setting.token_expire_in');

        //存入tp5自带的缓存
        //$request = cache($key,$value,$expire_in);
        $request = Cache::set($key,$value,$expire_in);
        if(!$request) {
            throw new TokenException([
                'msg' => '服务器缓存异常',
                'errorCode' => 10005
            ]);
        }
        //返回令牌
        return $key;
    }
    private function prepareCachedValue($wxResult,$uid){
        $cachedValue = $wxResult;
        $cachedValue['uid'] = $uid;
        $cachedValue['scope'] = ScopeEnum::User;
        $cachedValue['vip'] =$this->getUserVipById($uid);
        //$cachedValue['scope'] = 15;
        return $cachedValue;
    }
    private function newUser($openid) {
        $user = UserModel::create([
           'openid' => $openid
        ]);
        return $user->id;
    }
    private function processLoginError($wxResult) {
        throw new WeChatException([
            'msg' => $wxResult['errmsg'],
            'errorCode' => $wxResult['errcode'],
        ]);
    }

    private function getUserVipById($uid){
        $user = UserModel::get($uid);
        if(!$user){
            throw new UserException();
        }
        $vip = $user->vip;
        return $vip;
    }
}